#coding=utf-8
from django.http import JsonResponse
# from django.shortcuts import HttpResponse
from .import models,encryption
import json
from adminapi.models import User
from guestapi.models import GuestInfo
from rest_framework.decorators import api_view
from rest_framework.authtoken.models import Token
from django.contrib import auth
from django.contrib.auth import login, logout
from .import encryption
from adminapi.models import WxInfo

@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'add':
                return wx_add(request)
            elif action == 'del':
                return wx_del(request)
            elif action == 'list':
                return wx_list(request)

            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def wx_list(request):
    try:
        data = json.loads(request.body)
        userid = data['userid']
        index = WxInfo.objects.filter(userid=userid).values()
        count = WxInfo.objects.filter(userid=userid).count()

        return JsonResponse({'ret':0,'data':list(index),'count':count})
    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def wx_add(request):
    data = json.loads(request.body)  
    try:
        unionid = data['unionid']
        userid = data['userid']
        name = data['name']
        openid = data['openid']

        if WxInfo.objects.filter(unionid=unionid).exists():
            return JsonResponse({
            'ret': 1,
            'msg': "该微信已被绑定"
            })
        WxInfo.objects.create(
        unionid = unionid,
        userid = userid,
        name = name,
        openid = openid
        )

        return JsonResponse({'ret':0})

    except Exception as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息添加失败，发生异常:{}".format(e)
            })

def wx_del(request):
    data = json.loads(request.body)
    unionid = data['unionid']
    try:
        if WxInfo.objects.filter(unionid=unionid).exists():
            index = WxInfo.objects.get(unionid=unionid)
            index.delete()
        else:
            return JsonResponse({
            'ret': 1,
            'msg': "不存在该管理员"
            })
    except Exception as e:
        return JsonResponse({
            'ret': 1,
            'msg': "删除失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0})

@api_view(['POST'])
def signin(request):
    try:
        data = json.loads(request.body)
        signin_type = data['signin_type']
        if signin_type == 'pc':
            username = data['username']
            password = data['password']
            ps = encryption.encrypt(password).AES_Decrypt()
            user = auth.authenticate(username=username, password=ps)
        elif signin_type == 'wx':
            key = data['key']
            unionid = encryption.encrypt(key).AES_Decrypt()
            wx_data =  WxInfo.objects.get(unionid=unionid)
            index = User.objects.get(openid=wx_data.openid)

            ps = encryption.encrypt(index.password_md5).AES_Decrypt()
            user = auth.authenticate(username=index.username , password=ps)
        elif signin_type == 'card':
            card = data['card']
            unionid = data['unionid']
            nbr = encryption.encrypt(card).AES_Decrypt()
            uid = encryption.encrypt(unionid).AES_Decrypt()
            if GuestInfo.objects.filter(guest_nbr=nbr).exists():
                if GuestInfo.objects.filter(guest_unionid=unionid).exists():
                    return JsonResponse({'ret': 3, 'msg': '该微信账号已绑定其他住户'})
                else:
                    re = GuestInfo.objects.get(guest_nbr=nbr)
                    re.guest_unionid = uid
                    re.save()

                    openid = re.guest_openid
                    index = User.objects.get(openid=openid)

                    ps = encryption.encrypt(index.password_md5).AES_Decrypt()
                    user = auth.authenticate(username=index.username , password=ps)
            else:
                return JsonResponse({'ret': 3, 'msg': '该住户不存在'})

        elif signin_type == 'unionid':
            guest_unionid = data['unionid']
            unionid = encryption.encrypt(guest_unionid).AES_Decrypt()
            if GuestInfo.objects.filter(guest_unionid=unionid).exists():
                re = GuestInfo.objects.get(guest_unionid=unionid)
                openid = re.guest_openid
                index = User.objects.get(openid=openid)

                ps = encryption.encrypt(index.password_md5).AES_Decrypt()
                user = auth.authenticate(username=index.username , password=ps)
            else:
                return JsonResponse({'ret': 4, 'msg': '该微信账号不存在'})
            
        if user is not None:
            if user.is_active:
                # if user.is_superuser:
                login(request,user)
                # 校验通过
                # 删除原有的Token
                old_token = Token.objects.filter(user=user)
                old_token.delete()
                # 创建新的Token
                token = Token.objects.create(user=user)

                # 待加密文本
                aes_usertype = str(user.usertype)
                aes_is_active = ''
                if user.is_active:
                    aes_is_active = '1'
                else:
                    aes_is_active = '0'
                aes_is_active = str(user.is_active)
                #调用加密工具
                usertype_result = encryption.encrypt(aes_usertype).encryp_add()
                active_result = encryption.encrypt(aes_is_active).encryp_add()
                openid_result = encryption.encrypt(user.openid).encryp_add()

                return JsonResponse({'ret': 0 ,"username": user.username, "token":token.key,
                "usertypen": usertype_result , "is_active": active_result , "user_mode": user.user_mode ,"openid": openid_result,"userid":user.id})

            else:
                return JsonResponse({'ret': 2, 'msg': '用户已经被禁用'})
        else:
            return JsonResponse({'ret': 1, 'msg': '用户名或者密码错误'})
    except Exception as e:
        return JsonResponse({'ret': 3 , 'msg':e})

# 登出处理
@api_view(['POST'])
def signout(request):
    # 使用登出方法
    try:
        logout(request)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"登出失败，发生异常:{}".format(e)})  
    return JsonResponse({'ret': 0 })

@api_view(['POST'])
def addopenid(request):
    try:
        if request.user.is_authenticated: 
            if request.user.is_active:
                data = json.loads(request.body)
        # 直接调用 models中的添加 用户 的代码    
        ret = models.User.open(data)

        return  JsonResponse(ret)

    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})


@api_view(['POST'])
def existence(request):
    try:

        data = json.loads(request.body)
        openid = data['openid']
        if User.objects.filter(openid=openid).exists():
            return JsonResponse({'ret':0,'existence':0})
        else:
            return JsonResponse({'ret':0,'existence':1})

    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})


@api_view(['POST'])
def adduser(request):
    try:
        if request.user.is_authenticated: 
            if request.user.is_superuser:
                data = json.loads(request.body)
        # 直接调用 models中的添加 用户 的代码    
        ret = models.User.add(data)

        return  JsonResponse(ret)

    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})


@api_view(['POST'])
def deluser(request):
    try:
        if request.user.is_authenticated: 
            if request.user.is_superuser:

                data = json.loads(request.body)             
                # 直接调用 models中的删除 用户 的代码    
                ret = models.User.dele(data)

                return  JsonResponse(ret)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})
    
@api_view(['POST'])
def getlist(request):
    try:
        if request.user.is_authenticated: 
            # if request.user.is_superuser:
            data = json.loads(request.body)
            pagenbr = int(data['pagenbr'])
            ret = models.User.ulist(data,pagenbr)
            return  JsonResponse(ret)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})

@api_view(['POST'])
def getlist_total(request):
    try:
        if request.user.is_authenticated: 
            # if request.user.is_superuser:  
            data = json.loads(request.body)
            if 'username' in data:
                uname = data['username']
            else:
                uname=request.user.username
            ret = models.User.ulist_total(data,uname)
            return  JsonResponse(ret)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})

@api_view(['POST'])
def re_user_active(request):
    try:
        if request.user.is_authenticated: 
            if request.user.is_superuser:  
                data = json.loads(request.body)             
                ret = models.User.re_active(data)
                return  JsonResponse(ret)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})

@api_view(['POST'])
def re_user_pass(request):
    try:
        if request.user.is_authenticated: 
            if request.user.is_superuser:  
                data = json.loads(request.body)           
                ret = models.User.re_pass(data)
                return  JsonResponse(ret)
    except Exception as e:
        return JsonResponse({'ret': 1 , 'msg':"发生异常:{}".format(e)})


